package com.restaurantonlineorder.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.restaurantonlineorder.enums.RoleEnum;
import com.restaurantonlineorder.gateway.properties.RestaurantGatewayProperties;
import com.restaurantonlineorder.response.BaseResult;
import com.restaurantonlineorder.response.BaseResultCode;
import com.restaurantonlineorder.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author 熊宇
 * @date 2022/7/24 15:07
 * @description 全局过滤器
 */
@Component
@Slf4j
public class DefaultGlobalFilter implements GlobalFilter, Ordered {

    private static final PathMatcher PATH_MATCHER = new AntPathMatcher();
    private static final String AUTHENTIC = "Authentication";

    @Resource
    private RestaurantGatewayProperties restaurantGatewayProperties;


    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求路径
        String path = exchange.getRequest().getURI().getPath();
        log.info("进入全局过滤器，请求路径为：{}", path);
        if (shouldSkip(path)) {
            return chain.filter(exchange);
        }

        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst(AUTHENTIC);
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer dataBuffer = response.bufferFactory().allocateBuffer();

        //toke是否为空
        if (StrUtil.isBlankOrUndefined(token)) {
            BaseResult<Void> failure = BaseResult.failure(BaseResultCode.PERMISSION_NO_ACCESS);
            byte[] mes = JSONUtil.toJsonStr(failure).getBytes("UTF-8");
            dataBuffer.write(mes);
            return response.writeWith(Mono.just(dataBuffer));
        }


        return checkAuth(token, exchange, chain);
    }


    /***
     * 校验
     * @param token
     * @param exchange
     * @param chain
     * @return
     */
    @SneakyThrows
    private Mono<Void> checkAuth(String token, ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求路径
        String path = exchange.getRequest().getURI().getPath();

        ServerHttpResponse response = exchange.getResponse();
        DataBuffer dataBuffer = response.bufferFactory().allocateBuffer();
        /**
         * 校验token
         */
        Claims claims = JwtUtil.parseToken(token);

        if (claims != null) {
            String role = (String) claims.get("role");
            if (RoleEnum.BUYER.getRoleName().equals(role) && PATH_MATCHER.match(RestaurantGatewayProperties.BUYERPATH, path) ||
                    RoleEnum.SELLER.getRoleName().equals(role) && PATH_MATCHER.match(RestaurantGatewayProperties.SELLERPATH, path)) {
                //添加head信息
                ServerWebExchange webExchange = wrapHeader(exchange, claims.getSubject());
                return chain.filter(webExchange);
            }
        }

        BaseResult<Void> failure = BaseResult.failure(BaseResultCode.PERMISSION_NO_ACCESS);
        byte[] mes = JSONUtil.toJsonStr(failure).getBytes("UTF-8");
        dataBuffer.write(mes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @SneakyThrows
    private ServerWebExchange wrapHeader(ServerWebExchange exchange, String phone) {
        log.info("phone:{}", phone);
        // 向headers中放入用户信息
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("phone", phone)
                .build();
        return exchange.mutate().request(request).build();
    }

    private boolean shouldSkip(String path) {
        for (String ignoreUrl : restaurantGatewayProperties.getIgnoreUrls()) {
            if (PATH_MATCHER.match(ignoreUrl, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
